package es.javamyadmin.ajax;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import es.javamyadmin.dao.TablesDAO;
import es.javamyadmin.modelo.Tables;

/**
 * Esta clase consulta las base de datos que hay en un servidor 
 * para mostrarlas
 * @author Emilio Javier Castillo Gonzalez y Hector Delgado Duran
 *
 */
public class ShowTablasAjax extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6469740521665384182L;

	/**
	 * doGet solo llama a doPost
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * Metodo que recoje los datos necesarios para consultar los detalles
	 * de las bases de datos y crea una lista a partir de ellas
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("---> En ShowTablas");
		
		String user = request.getParameter("usuario");
		String pass = request.getParameter("pass");
		String host = request.getParameter("servidor");
		String port = request.getParameter("puerto");
		String database = request.getParameter("bd");
		String text = "<select class='campo' name='tabla'>";
		TablesDAO listaTablas = new TablesDAO();
		listaTablas.setPath(getServletContext().getResourceAsStream("/WEB-INF/properties/mensajes.properties"));
		Iterator<Tables> lista = listaTablas.leerTables(user, pass, host, port, database).iterator();
		int contador = 1;
		while(lista.hasNext()){
			Tables tablas =  lista.next();
			text = text + "<option value='" + tablas.getNombreTable() + "'>" + tablas.getNombreTable() + "</option>";
			contador++;
		}
		if(contador == 1){
			text = text + "<li>No existe ninguna tabla</li>";
		}
				
		text = text + "</select>";
		
	    PrintWriter out = new PrintWriter(new OutputStreamWriter( response.getOutputStream(),"UTF8"), true);
		try{
			out.print(text);
		}finally{
			out.close();
		}
	}

}
